package com.qust.EnDecryption.monitor;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    Thread thread = null;
    Boolean flag = false;
    long millis = 1000;
    String startKey = "start";
    String stopKey = "stop";

    @Override
    public void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        // 处理消息

        if (msg.text().equals(startKey)) {
            flag = false;
            if (thread == null) {
                thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        log.debug("启动监控线程");
                        while (true) {
                            try {
                                if (flag) {
                                    log.debug("关闭监控线程");
                                    break;
                                }
                                ctx.channel().writeAndFlush(new TextWebSocketFrame("Server received: " + SystemInfoUtils.getCMInfo()));
                                Thread.sleep(millis);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                });
                thread.start();
            }
        } else if (msg.text().equals(stopKey)) {
            flag = true;
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        flag = false;
        super.channelInactive(ctx);
    }
}